#!/bin/bash

datetime=`date +%Y%m%d_%H%M%S`

if [ -z "$1" ];then
    default_path=`pwd`
else
    default_path=$1
fi

# determine if there is a / at the end of the path
if [ ${default_path: -1} == "/" ];then
    default_path_treenum=`echo $default_path | awk -F"/" '{print NF-1}'`
    tar_path=`echo $default_path | awk -F"/" '{print $(NF-1)}'`/
else
    default_path_treenum=`echo $default_path | awk -F"/" '{print NF}'`
    tar_path=`echo $default_path | awk -F"/" '{print $(NF)}'`
fi
printf "\033[32m[Info] directory num: $default_path_treenum \033[0m\n"
printf "\033[32m[Info] tar path: $tar_path \033[0m\n"

# get cd path
cd_begin_path=`echo ${default_path%$tar_path}`
for((i=0;i<$default_path_treenum-1;i++))
do
    cd_end_path+=../
done
printf "\033[32m[Info] cd begin path: $cd_begin_path \033[0m\n"
printf "\033[32m[Info] cd end path: $cd_end_path \033[0m\n"

cd $cd_begin_path
tar -zcvf $cd_begin_path${datetime}.tar.gz ${tar_path}
